# django
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.shortcuts import render_to_response
# own package
import models
# external
from mutagen.mp3 import MP3
from mutagen.easyid3 import EasyID3
# native
import re, os, dircache

MP3_RE = re.compile(r'\.mp3$', re.I)

def index(request):
    tracks = gettracks(settings.MUSIC_PATH)
    return render_to_response('playlist/index.html', 
        { 'tracks' : tracks })

def embedded(request):
    # don't need to assign tracks here, they're fetch for us
    return render_to_response('playlist/embedded.html', {})
    
def xspf(request):
    tracks = gettracks(settings.MUSIC_PATH)
    return render_to_response('playlist/xspf.xml', 
        { 'tracks' : tracks,
          'SERVER_NAME' : request.META['SERVER_NAME'],
          'SERVER_PORT' : request.META['SERVER_PORT'] })

def track_list(request):
    tracks = gettracks(settings.MUSIC_PATH)
    return render_to_response('playlist/track_list.html', 
        { 'tracks' : tracks })

def gettracks(path):
    items = dircache.listdir(path)
    return [ trackFromMP3(os.path.join(path, item))
        for item in filter(istrack, items)]
        
def istrack(item):
    if MP3_RE.search(item):
        return True
    return False
    
def trackFromMP3(mp3):
    audio = MP3(mp3, ID3=EasyID3)
    title = audio['title'][0]
    length = int(round(audio.info.length))
    location = settings.MUSIC_EXT_PATH + mp3.split('/').pop()
    return models.Track(title=title, length=length, location=location)


